package com.github.pig.training.util;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pig.admin.model.entity.SysUser;
import com.github.pig.admin.service.SysUserService;
import com.github.pig.admin.service.impl.SysUserServiceImpl;
import com.github.pig.common.constant.CommonConstant;
import com.github.pig.common.vo.UserVO;
import com.github.pig.sales.entity.SalesIntentionFlowup;
import com.github.pig.training.entity.TrainingStudent;
import com.github.pig.training.service.ITrainingStudentService;
import com.github.pig.training.service.impl.TrainingStudentServiceImpl;
import org.apache.catalina.User;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.reflections.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;


import java.io.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

public class ReadData {

    private static ITrainingStudentService trainingStudentService = new TrainingStudentServiceImpl();

    private static SysUserService userService = new SysUserServiceImpl();


//    public static void main(String ages[]){
//        System.err.println("开始读取Execl...");
//        setTrainingStudent();
//
//        System.err.println("取数结束...");
//    }

    /**
     * 添加学员信息
     */
    public static List<TrainingStudent> setTrainingStudent(List<SysUser> users){
        List<TrainingStudent> list = new ArrayList<>();
        try{
            File excel = new File("C:/Users/Administrator/Desktop/【客户管理】-全部11.xls");
            String[][] data = getData(excel,1);
            List<SalesIntentionFlowup> listUp = new ArrayList<>();
            String[][] dataS = getData(excel,0);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//时间格式
            for (String[] str : data) {
                 TrainingStudent t = new TrainingStudent();
                    t.setFname(str[0].trim());
                    t.setCreateTime(sdf.parse(str[1]));
                    t.setCollectDate(sdf.parse(str[1]));
                    String sex = "男".equals(str[2].trim())?"0":("女".equals(str[2].trim())?"1":null);
                    if(!Utils.isEmpty(sex)){ t.setSex(Integer.valueOf(sex)); }
                    t.setTel2(getTelephone(str[4]));
                    t.setTel1(getTelephone(str[5]));
                    t.setChannel("员工推广".equals(str[14].trim())?"2403":"2404");
                    t.setFollowUpStatus(str[33].trim().contains("成交客户")?"1603":"1601");
                    t.setIntentionLevel(str[48].trim().contains("A")?"1501":(str[48].trim().contains("B")?"1502":(str[48].trim().contains("C")?"1503":"1504")));
                    t.setLabel(str[19].trim());
                    for(SysUser u : users){
                        if(u.getName().equals(str[23].trim())){ t.setFollowUpUser(u.getUserId()); }
                    }
                    t.setRemark(str[25].trim());
                    t.setCurrentCallCount(0);
                    t.setIdCard(str[30].trim());
                    t.setSchool(str[33].trim().contains("江北")?"2002":(str[33].trim().contains("杨家")?"2001":"2003"));
                    t.setWechat(str[36].trim());
                    t.setDelFlag(CommonConstant.STATUS_NORMAL);
                list.add(t);
//                trainingStudentService.insert(t);
            }
//            trainingStudentService.insertOrUpdateAllColumnBatch(list);
//            System.err.println(getData(excel,1).toString());
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }

    public static String[][] getData(File file, int ignoreRows)
            throws FileNotFoundException, IOException {
        List<String[]> result = new ArrayList<String[]>();
        int rowSize = 0;
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(
                file));
        // 打开HSSFWorkbook
        POIFSFileSystem fs = new POIFSFileSystem(in);
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFCell cell = null;
        for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {
            HSSFSheet st = wb.getSheetAt(sheetIndex);
            // 第一行为标题，不取
            for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) {
                HSSFRow row = st.getRow(rowIndex);
                if (row == null) {
                    continue;
                }
                int tempRowSize = row.getLastCellNum() + 1;
                if (tempRowSize > rowSize) {
                    rowSize = tempRowSize;
                }
                String[] values = new String[rowSize];
                Arrays.fill(values, "");
                boolean hasValue = false;
                for (short columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex++) {
                    String value = "";
                    cell = row.getCell(columnIndex);
                    if (cell != null) {
                        // 注意：一定要设成这个，否则可能会出现乱码,后面版本默认设置
                        //cell.setEncoding(HSSFCell.ENCODING_UTF_16);
                        switch (cell.getCellType()) {
                            case HSSFCell.CELL_TYPE_STRING:
                                value = cell.getStringCellValue();
                                break;
                            case HSSFCell.CELL_TYPE_NUMERIC:
                                if (HSSFDateUtil.isCellDateFormatted(cell)) {
                                    Date date = cell.getDateCellValue();
                                    if (date != null) {
                                        value = new SimpleDateFormat("yyyy-MM-dd").format(date);
                                    } else {
                                        value = "";
                                    }
                                } else {
                                    value = new DecimalFormat("0").format(cell.getNumericCellValue());
                                }
                                break;
                            case HSSFCell.CELL_TYPE_FORMULA:
                                // 导入时如果为公式生成的数据则无值
                                if (!cell.getStringCellValue().equals("")) {
                                    value = cell.getStringCellValue();
                                } else {
                                    value = cell.getNumericCellValue() + "";
                                }
                                break;
                            case HSSFCell.CELL_TYPE_BLANK:
                                break;
                            case HSSFCell.CELL_TYPE_ERROR:
                                value = "";
                                break;
                            case HSSFCell.CELL_TYPE_BOOLEAN:
                                value = (cell.getBooleanCellValue() == true ? "Y" : "N");
                                break;
                            default:
                                value = "";
                        }
                    }
                    if (columnIndex == 0 && value.trim().equals("")) {
                        break;
                    }
                    values[columnIndex] = rightTrim(value);
                    hasValue = true;
                }
                if (hasValue) {
                    result.add(values);
                }
            }
        }
        in.close();
        String[][] returnArray = new String[result.size()][rowSize];
        for (int i = 0; i < returnArray.length; i++) {
            returnArray[i] = (String[]) result.get(i);
        }
        return returnArray;
    }


    /**
     * 去掉字符串右边的空格
     *
     * @param str 要处理的字符串
     * @return 处理后的字符串
     */

    public static String rightTrim(String str) {
        if (str == null) {
            return "";
        }
        int length = str.length();
        for (int i = length - 1; i >= 0; i--) {
            if (str.charAt(i) != 0x20) {
                break;
            }
            length--;
        }
        return str.substring(0, length);
    }

    /**
     * 电话号码截取
     */
    public static String getTelephone(String str){
        if(str!=null&&str.trim().length()>4&&str.substring(0,4).equals("+86 ")){
            return str.trim().substring(4);
        }
        return null;
    }
}
